<template>
  <div class="organization">
    <div class="create-button">
      <a-button v-if="hasEditPermission" @click="openModal">
        <template #icon>
          <e-icon type="add" color="#fff" font-size="18px" style="cursor: pointer; margin-left: -2px" />
        </template>
        <span style="margin-left: 10px">Create</span>
      </a-button>
    </div>
    <search @search="handleSearch" @reset="handleReset">
      <div style="display: flex">
        <SearchInput searchText="Organization">
          <a-input v-model:value="organization" />
        </SearchInput>
      </div>
    </search>
    <e-container style="margin-top: 24px">
      <a-spin :spinning="loading" tip="Loading...">
        <a-table
          :columns="columns"
          :data-source="data"
          class="ant-table-striped"
          :expandIconColumnIndex="6"
          :expanded-row-keys="expandedRowKeys"
          :pagination="false"
          :row-class-name="(_record, index) => (index % 2 === 0 ? 'table-striped' : null)"
          @change="sortChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'operate' && hasEditPermission">
              <span style="cursor: pointer; margin-right: 36px" @click="handleEdit(record)">
                <e-icon type="edit" color="#3c6cfe" font-size="12px" /><span style="color: #3c6cfe; margin-left: 2px"
                  >Edit</span
                >
              </span>
              <a-popconfirm
                title="Are you sure delete this task?"
                ok-text="Yes"
                cancel-text="No"
                @confirm="handleDelete(record)"
              >
                <span v-if="record.isDelete" style="cursor: pointer">
                  <e-icon type="delete" color="#fc4b3b" font-size="12px" /><span
                    style="color: #fc4b3b; margin-left: 2px"
                    >Delete</span
                  >
                </span>
              </a-popconfirm>
            </template>
          </template>
          <template #expandedRowRender="{ record }">
            <div v-if="!record.isDelete" class="expand">
              <div class="expand-top">
                <div class="expand-top-item">Client Number</div>
                <div class="expand-top-item">Client Name</div>
                <div class="expand-top-item">Abbreviation</div>
                <div class="expand-top-item">Status</div>
                <div class="expand-top-item">Operate</div>
              </div>
              <div v-for="(item, index) in record.clientOrgMsgList" :key="index" class="expand-list">
                <div class="list-item">{{ item.clientNum }}</div>
                <div class="list-item">{{ item.fullName }}</div>
                <div class="list-item">{{ item.shortName }}</div>
                <div class="list-item">{{ item.statusName }}</div>
                <div class="list-item" style="color: #a9b5c9">
                  <span style="cursor: pointer" @click="changeOrganization(item)">
                    <e-icon type="edit" style="margin-top: 5px; margin-right: 4px" />
                    <span>Change Organization</span>
                  </span>
                </div>
              </div>
            </div>
          </template>
          <template #expandIcon="{ expanded, record }">
            <e-icon
              v-if="record.client > 0"
              :type="expanded ? 'Hidden' : 'DropDown'"
              color="#a9b5c9"
              font-size="20px"
              style="cursor: pointer"
              @click="handleRowExpand(expanded, record)"
            />
          </template>
          <template #emptyText>
            <e-empty>
              <template #description>
                <div>No Data</div>
              </template>
            </e-empty>
          </template>
        </a-table>
      </a-spin>
      <div v-if="total > 0" class="pagination">
        <a-pagination
          v-model:current="current"
          v-model:pageSize="pageSize"
          :total="total"
          show-less-items
          :show-size-changer="false"
          @change="changeSize"
        />
      </div>
    </e-container>

    <a-modal
      v-model:visible="visible"
      wrap-class-name="primary-modal"
      width="888px"
      :title="isAdd ? 'Add Organization' : 'Edit Organization'"
      @cancel="handleCancel"
    >
      <a-form ref="formRef" layout="vertical" :model="formState" :rules="rules">
        <a-form-item ref="oName" label="Organization Name" name="oName">
          <a-input v-model:value="formState.oName" autocomplete="off"></a-input>
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button key="back" @click="handleCancel">Cancel</a-button>
        <a-button key="submit" type="primary" @click="handleSave">Save</a-button>
      </template>
    </a-modal>
    <Modal v-model:visible="orVisible" :clientId="clientId" :type="type" @cancel="handleOrCancel" @getList="getList" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, inject, computed } from 'vue'
import { useStore } from 'vuex'
import { EDIT_SUCCEEDED, CREATED_SUCCESSFULLY, DELETE_SUCCEEDED } from '@/constants/message.js'
import EContainer from '@/components/EContainer.vue'
import EEmpty from '@/components/EEmpty.vue'
import EIcon from '@/components/EIcon.vue'
import Search from '../../components/Search.vue'
import SearchInput from '../../components/SearchInput.vue'
import Modal from './components/Modal.vue'
import others from '@/api/others.js'
import pageColumns from '@/assets/script/page_columns.js'
const store = useStore()
const hasEditPermission = computed(() => store.getters['user/isPrimaryCSO'] || store.getters['user/isSalesSupport'])
const { message } = inject('Feedback')
const columns = reactive(pageColumns.organization)
const data = ref([])
const clientId = ref()
const type = ref(0)
const organization = ref('')
const expandedRowKeys = ref([])
const current = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const formRef = ref()
const formState = reactive({
  oName: undefined
})
const isAdd = ref(true)
const visible = ref(false)
const orVisible = ref(false)
const updateId = ref()
const rules = {
  oName: [
    {
      required: true,
      whitespace: true,
      message: 'Please input Organization Name.',
      trigger: 'blur'
    }
  ]
}
const sort = ref('')
const order = ref('')
/**
 * 行展开、收起
 * @param expanded
 * @param record
 */
const handleRowExpand = async (expanded, record) => {
  if (expanded) {
    expandedRowKeys.value.splice(
      expandedRowKeys.value.findIndex(key => key === record.key),
      1
    )
  } else {
    expandedRowKeys.value.push(record.key)
  }
}
/**
 * 获取列表
 */
const getList = () => {
  loading.value = true
  others
    .organizationQuery({
      page: {
        pageRows: pageSize.value,
        pageIndex: current.value,
        sort: sort.value,
        order: order.value,
        total: 0
      },
      organizationName: organization.value.trim()
    })
    .then(res => {
      if (res.code === 2000) {
        for (let i = 0; i < res.data.length; i++) {
          res.data[i].key = i
        }
        data.value = res.data
        total.value = res.total
        expandedRowKeys.value = []
      }
    })
    .finally(() => {
      setTimeout(() => {
        loading.value = false
      }, 30)
    })
}
/**
 * 切换页码
 * @param cur
 */
const changeSize = cur => {
  current.value = cur
  getList()
}
/**
 * 搜索
 */
const handleSearch = () => {
  current.value = 1
  getList()
}
/**
 * 清空
 */
const handleReset = () => {
  organization.value = ''
  current.value = 1
  getList()
}
/**
 * 编辑
 * @param record
 */
const handleEdit = record => {
  visible.value = true
  isAdd.value = false
  formState.oName = record.clientOrganizationName
  updateId.value = record.id
}
/**
 * 删除
 * @param record
 */
const handleDelete = record => {
  others
    .organizationDelete({
      id: record.id
    })
    .then(res => {
      if (res.code === 2000) {
        current.value = 1
        getList()
        message.success(DELETE_SUCCEEDED)
      }
    })
}
/**
 * 打开模态框
 */
const openModal = () => {
  visible.value = true
}
/**
 * 取消模态框
 */
const handleCancel = () => {
  formState.oName = undefined
  visible.value = false
}
/**
 * 取消模态框
 */
const handleOrCancel = () => {
  orVisible.value = false
  type.value = 0
}
/**
 * 提交数据
 */
const handleSave = () => {
  formRef.value
    .validate()
    .then(() => {
      if (isAdd.value) {
        others
          .organizationCreate({
            organizationName: formState.oName.trim()
          })
          .then(res => {
            if (res.code === 2000) {
              visible.value = false
              formRef.value.resetFields()
              formState.oName = undefined
              current.value = 1
              getList()
              message.success(CREATED_SUCCESSFULLY)
            }
          })
      } else {
        others
          .organizationUpdate({
            id: updateId.value,
            organizationName: formState.oName.trim()
          })
          .then(res => {
            if (res.code === 2000) {
              visible.value = false
              formRef.value.resetFields()
              formState.oName = undefined
              getList()
              message.success(EDIT_SUCCEEDED)
            }
          })
      }
    })
    .catch(() => {})
}
/**
 * 排序
 * @param p
 * @param f
 * @param s
 */
const sortChange = (p, f, s) => {
  if (s.order === 'ascend') {
    order.value = 'asc'
    sort.value = s.columnKey
  } else if (s.order === 'descend') {
    order.value = 'desc'
    sort.value = s.columnKey
  } else {
    order.value = ''
    sort.value = ''
  }
  getList()
}
/**
 * 修改组织弹窗
 * @param item
 */
const changeOrganization = item => {
  type.value = 1
  clientId.value = item.id
  orVisible.value = true
}
/**
 * 初始化
 */
onMounted(() => {
  getList()
})
</script>

<style lang="less" scoped>
@import '@/assets/style/reset_table';
@import '@/assets/style/reset_form';
.expand {
  width: 100%;
  border-left: 1px solid @border-color;
  background-color: @white;
  .expand-top {
    width: 100%;
    height: 40px;
    background-color: @milk;
    display: flex;
    box-sizing: border-box;
    .expand-top-item {
      flex: 1;
      border-right: 1px solid @border-color;
      display: flex;
      align-items: center;
      color: @text-gray;
      padding-left: 12px;
      font-size: 14px;
    }
  }
  .expand-list {
    width: 100%;
    height: 40px;
    display: flex;
    box-sizing: border-box;
    border-top: 1px solid @border-color;
    .list-item {
      flex: 1;
      border-right: 1px solid @border-color;
      display: flex;
      align-items: center;
      color: @black-85p;
      font-size: 14px;
      padding-left: 12px;
    }
  }
}
.create-button {
  position: absolute;
  top: 64px;
  right: 24px;
  z-index: 99;
  .ant-btn {
    width: 94px;
    height: 32px;
    background-color: @primary-color;
    border-radius: 2px;
    color: @white;
    font-size: 14px;
  }
}
</style>
<route lang="yaml">
name: Organization View
path: '/organization/organization-view'
meta:
  sort: 0
  roles: isPrimaryCSO, isSalesSupport
</route>
